<template>
  <view class="page-container">
    <!-- 页面内容区域 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      :style="{ height: scrollViewHeight + 'px' }"
      @scrolltolower="onReachBottom"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 搜索栏 -->
      <view class="search-bar">
        <view class="search-input" @click="goToSearch">
          <svg class="icon-search" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
            <path d="M935.8 882.9c8 9.3 12 19.6 12 31 0 12.6-4.5 23.5-13.5 32.5-8.5 8.8-20.3 13.7-32.5 13.5-5.3 0-10.5-0.9-15.5-2.5s-9.5-4.1-13.5-7.4l-5-4-247.1-249c-59.5 42-125.8 62.9-199.2 62.9-7.3 0-14.8-0.3-22.4-1-7.6-0.6-15.1-1.6-22.6-3-50.8-5.8-99.5-23.6-142.1-52-46.7-30-84.1-69.6-112-118.9-13.5-23-24.1-47.5-31.5-72.9-7.7-25.7-12.3-52.2-14-79-1.6-26.8-0.1-53.6 4.5-80 6.7-42.6 21.6-83.6 44-120.4 22.2-37.1 51.5-69.5 86-95.5 29.3-23.3 62.2-41.3 98.5-54 35.8-12.6 73.6-19 111.6-19 16 0 31.4 1 46.1 3 39.4 5.3 77.1 17.3 113 35.9 35.4 18.2 67.2 42.5 94.1 72 31.3 32.7 55.1 71.3 71.6 116 16.3 44.7 23.5 90 21.5 136-2.7 76.6-29 145.7-79.1 207L936.9 883h-1.1zM715.7 426c2.2-41-4.6-81.9-20-120-8.7-23.4-20.5-45.6-35.1-65.9-14.7-20.6-31.8-39.2-51.5-55.5-19.3-16.2-40.7-29.8-63.6-40.5-48.7-22.6-102.7-31.2-156-24.9-3 0-6 0.3-9 1l-6 1c-42.6 6.6-83.2 22.9-118.6 47.5-35.6 24.2-65.2 56.1-86.5 93.5-24.6 40.7-38.2 86-40.6 136-2.4 50 6.8 96.4 27.5 139 17.3 38.6 43.2 72.7 75.5 99.9 32 27.5 69.8 47.7 110.5 59 42.7 12 85.7 14.4 129.1 7 22.8-4 44.9-10.7 66-20 21-9.2 41-20.7 59.6-34.5 18.5-13.7 35.2-29.5 50.1-47 15-17.7 27.5-36.8 37.6-57.5 18.6-36.7 29.1-77 31-118.1z" fill="#999999"/>
          </svg>
          <text class="search-placeholder">搜索商品</text>
        </view>
      </view>
      
      <!-- 轮播图 -->
      <view class="swiper-container">
        <swiper 
          class="swiper" 
          :indicator-dots="true" 
          :autoplay="true" 
          :circular="true"
          :interval="3000"
          :duration="500"
          indicator-active-color="#ff6b6b"
        >
          <swiper-item v-for="(item, index) in banners" :key="index">
            <image 
              :src="item.image" 
              class="swiper-image" 
              mode="aspectFill"
              @click="onBannerClick(item)"
            />
          </swiper-item>
        </swiper>
      </view>
      
      <!-- 分类入口 -->
      <view class="category-section">
        <view 
          v-for="category in categories" 
          :key="category.id"
          class="category-item"
          @click="goToCategory(category.id)"
        >
          <image :src="category.icon" class="category-icon" mode="aspectFit" />
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
      
      <!-- 书籍推荐 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">书籍推荐</text>
          <text class="section-more" @click="goToBookList('recommend')">更多 ></text>
        </view>
        <scroll-view scroll-x class="scroll-list" :show-scrollbar="false">
          <view class="scroll-content">
            <view 
              v-for="book in recommendedBooks" 
              :key="book.id"
              class="book-item"
              @click="goToDetail(book.id)"
            >
              <view class="book-cover-container">
                <image :src="book.cover" class="book-cover" mode="aspectFill" />
                <text v-if="book.tag" class="book-tag">{{ book.tag }}</text>
              </view>
              <text class="book-title">{{ book.title }}</text>
              <view class="book-info">
                <text class="book-price">¥{{ book.price }}</text>
                <text class="book-sales">已售{{ book.sales }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 新品上架 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">新品上架</text>
          <text class="section-more" @click="goToBookList('new')">更多 ></text>
        </view>
        <view class="grid-list">
          <view 
            v-for="book in newBooks" 
            :key="book.id"
            class="grid-item"
            @click="goToDetail(book.id)"
          >
            <view class="book-cover-container">
              <image :src="book.cover" class="book-cover" mode="aspectFill" />
              <text class="book-new-tag">NEW</text>
            </view>
            <text class="book-title">{{ book.title }}</text>
            <view class="book-info">
              <text class="book-price">¥{{ book.price }}</text>
              <text class="book-stock">库存{{ book.stock }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 热门商品 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">热门商品</text>
          <text class="section-more" @click="goToBookList('hot')">更多 ></text>
        </view>
        <view class="hot-list">
          <view 
            v-for="(book, index) in hotBooks" 
            :key="book.id"
            class="hot-item"
            @click="goToDetail(book.id)"
          >
            <view class="hot-rank" :class="getRankClass(index)">{{ index + 1 }}</view>
            <image :src="book.cover" class="hot-cover" mode="aspectFill" />
            <view class="hot-info">
              <text class="hot-title">{{ book.title }}</text>
              <text class="hot-author">{{ book.author }}</text>
              <view class="hot-bottom">
                <text class="hot-price">¥{{ book.price }}</text>
                <text class="hot-sales">销量{{ book.sales }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部占位区域 -->
      <view class="bottom-placeholder" :style="{ height: placeholderHeight + 'px' }"></view>
      
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="showEmpty" class="empty-container">
        <image src="/static/empty.png" class="empty-image" mode="aspectFit" />
        <text class="empty-text">暂无商品数据</text>
      </view>
    </scroll-view>
    
    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        v-for="tab in tabList" 
        :key="tab.pagePath"
        class="tab-item"
        :class="{ active: currentTab === tab.pagePath }"
        @click="switchTab(tab)"
      >
        <view class="tab-icon">
          <image 
            :src="currentTab === tab.pagePath ? tab.selectedIconPath : tab.iconPath" 
            class="icon"
            mode="aspectFit"
          />
          <view v-if="tab.pagePath === 'bookshelf' && unreadCount > 0" class="bookshelf-badge">
            <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
          </view>
        </view>
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      banners: [
        { image: '/static/4.png', link: '/pages/promotion/promotion' },
        { image: '/static/5.png', link: '/pages/promotion/promotion' },
        { image: '/static/6.png', link: '/pages/promotion/promotion' }
      ],
      categories: [
        { id: 1, name: '文学小说', icon: '/static/category1.png' },
        { id: 2, name: '经济管理', icon: '/static/category2.png' },
        { id: 3, name: '科学技术', icon: '/static/category3.png' },
        { id: 4, name: '教育学习', icon: '/static/category4.png' },
        { id: 5, name: '生活艺术', icon: '/static/category5.png' }
      ],
      recommendedBooks: [],
      newBooks: [],
      hotBooks: [],
      loading: false,
      refreshing: false,
      showEmpty: false,
      scrollViewHeight: 0,
      placeholderHeight: 0,
      currentTab: 'index',
      unreadCount: 0,
      tabList: [
        {
          pagePath: 'index',
          text: '首页',
          iconPath: '/static/tabbar/home.png',
          selectedIconPath: '/static/tabbar/home-active.png'
        },
        {
          pagePath: 'category',
          text: '分类',
          iconPath: '/static/tabbar/category.png',
          selectedIconPath: '/static/tabbar/category-active.png'
        },
        {
          pagePath: 'bookshelf',
          text: '书架',
          iconPath: '/static/tabbar/bookshelf.png',
          selectedIconPath: '/static/tabbar/bookshelf-active.png'
        },
        {
          pagePath: 'profile',
          text: '我的',
          iconPath: '/static/tabbar/profile.png',
          selectedIconPath: '/static/tabbar/profile-active.png'
        }
      ]
    }
  },
  onLoad() {
    this.initPage()
    this.calcLayoutHeight()
  },
  onShow() {
    this.updateUnreadCount()
  },
  onPullDownRefresh() {
    this.loadHomeData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  onResize() {
    this.calcLayoutHeight()
  },
  methods: {
    async initPage() {
      if (!this.checkLogin()) {
        return
      }
      await this.loadHomeData()
    },
    
    checkLogin() {
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.redirectTo({ url: '/pages/login/login' })
        return false
      }
      return true
    },
    
    // 计算布局高度
    calcLayoutHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      const tabBarHeight = 100 // 底部导航栏高度
      
      this.scrollViewHeight = windowHeight - tabBarHeight
      this.placeholderHeight = tabBarHeight + (systemInfo.safeAreaInsets?.bottom || 0)
    },
    
    async loadHomeData() {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        this.recommendedBooks = this.generateMockBooks(6, 'recommend')
        this.newBooks = this.generateMockBooks(4, 'new')
        this.hotBooks = this.generateMockBooks(5, 'hot')
        
        this.showEmpty = !this.recommendedBooks.length && !this.newBooks.length && !this.hotBooks.length
        
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.recommendedBooks = this.generateMockBooks(6, 'recommend')
        this.newBooks = this.generateMockBooks(4, 'new')
        this.hotBooks = this.generateMockBooks(5, 'hot')
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadHomeData()
    },

    generateMockBooks(count, type) {
      const bookTitles = {
        recommend: ['三体全集', '百年孤独', '活着', '围城', '平凡的世界', '红楼梦'],
        new: ['时间简史新版', '人类简史', '未来简史', '原则'],
        hot: ['穷查理宝典', '思考快与慢', '刻意练习', '如何阅读一本书', '断舍离']
      }
      
      const authors = ['刘慈欣', '马尔克斯', '余华', '钱钟书', '路遥', '曹雪芹', '霍金', '尤瓦尔·赫拉利', '瑞·达利欧']
      const titles = bookTitles[type] || ['默认图书']
      
      return Array.from({ length: count }, (_, i) => ({
        id: Date.now() + i + (type === 'recommend' ? 1000 : type === 'new' ? 2000 : 3000),
        title: titles[i % titles.length],
        author: authors[i % authors.length],
        price: (Math.random() * 50 + 20).toFixed(2),
        sales: Math.floor(Math.random() * 1000) + 100,
        stock: Math.floor(Math.random() * 200) + 50,
        cover: `/static/book${(i % 8) + 1}.jpg`,
        tag: type === 'recommend' ? '推荐' : null
      }))
    },
    
    onReachBottom() {
      this.loadMore()
    },
    
    loadMore() {
      console.log('加载更多...')
    },
    
    // 修复底部导航切换
    switchTab(tab) {
      // 如果点击的是当前页面，滚动到顶部
      if (this.currentTab === tab.pagePath) {
        this.scrollToTop()
        return
      }
      
      // 更新当前选中的tab
      this.currentTab = tab.pagePath
      
      // 根据页面路径进行跳转
      const pageMap = {
        'index': '/pages/index/index',
        'category': '/pages/category/category',
        'bookshelf': '/pages/bookshelf/bookshelf',
        'profile': '/pages/profile/profile'
      }
      
      const targetUrl = pageMap[tab.pagePath]
      if (targetUrl) {
        // 使用 uni.switchTab 进行跳转
        uni.switchTab({
          url: targetUrl,
          fail: (err) => {
            console.error('跳转失败:', err)
            // 如果 switchTab 失败，尝试使用 redirectTo
            uni.redirectTo({
              url: targetUrl
            })
          }
        })
      }
    },
    
    scrollToTop() {
      // 在uni-app中，可以使用 uni.pageScrollTo 滚动到顶部
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    },
    
    updateUnreadCount() {
      const bookshelf = uni.getStorageSync('bookshelf') || []
      this.unreadCount = bookshelf.filter(book => book.status === 'unread').length
    },
    
    goToDetail(bookId) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${bookId}`
      })
    },
    
    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      })
    },
    
    goToCategory(categoryId) {
      uni.navigateTo({
        url: `/pages/category/category?id=${categoryId}`
      })
    },
    
    goToBookList(type) {
      uni.navigateTo({
        url: `/pages/book-list/book-list?type=${type}`
      })
    },
    
    onBannerClick(banner) {
      if (banner.link) {
        uni.navigateTo({
          url: banner.link
        })
      }
    },
    
    getRankClass(index) {
      if (index === 0) return 'rank-first'
      if (index === 1) return 'rank-second' 
      if (index === 2) return 'rank-third'
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
}

.content-scroll {
  flex: 1;
  overflow: hidden;
}

.search-bar {
  padding: 20rpx 30rpx;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-input {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #f5f5f5;
  border-radius: 50rpx;
  
  .icon-search {
    width: 32rpx;
    height: 32rpx;
    margin-right: 15rpx;
    flex-shrink: 0;
  }
  
  .search-placeholder {
    color: #999;
    font-size: 28rpx;
    flex: 1;
  }
}

.swiper-container {
  padding: 0 30rpx;
  margin-top: 20rpx;
}

.swiper {
  height: 300rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.swiper-image {
  width: 100%;
  height: 100%;
  display: block;
}

.category-section {
  display: flex;
  justify-content: space-around;
  padding: 40rpx 30rpx;
  background: #fff;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
  flex-wrap: wrap;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;
  margin-bottom: 20rpx;
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 15rpx;
}

.category-name {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

.section {
  background: #fff;
  margin: 30rpx;
  padding: 30rpx;
  border-radius: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-more {
  font-size: 26rpx;
  color: #999;
}

.scroll-list {
  white-space: nowrap;
  width: 100%;
}

.scroll-content {
  display: inline-flex;
}

.book-item {
  display: inline-flex;
  flex-direction: column;
  width: 200rpx;
  margin-right: 30rpx;
  flex-shrink: 0;
  
  &:last-child {
    margin-right: 0;
  }
}

.book-cover-container {
  position: relative;
  margin-bottom: 20rpx;
}

.book-cover {
  width: 200rpx;
  height: 280rpx;
  border-radius: 10rpx;
  display: block;
}

.book-tag, .book-new-tag {
  position: absolute;
  top: 10rpx;
  background: #ff6b6b;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  line-height: 1;
}

.book-tag {
  left: 10rpx;
}

.book-new-tag {
  right: 10rpx;
  background: #4cd964;
}

.book-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-price {
  font-size: 28rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.book-sales, .book-stock {
  font-size: 22rpx;
  color: #999;
}

.grid-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}

.grid-item {
  display: flex;
  flex-direction: column;
}

.hot-list {
  display: flex;
  flex-direction: column;
}

.hot-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.hot-rank {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  
  &.rank-first {
    background: #ff6b6b;
    color: #fff;
  }
  &.rank-second {
    background: #ffa726;
    color: #fff;
  }
  &.rank-third {
    background: #42a5f5;
    color: #fff;
  }
}

.hot-cover {
  width: 120rpx;
  height: 160rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.hot-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.hot-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hot-author {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 15rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hot-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hot-price {
  font-size: 28rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.hot-sales {
  font-size: 22rpx;
  color: #999;
}

.bottom-placeholder {
  width: 100%;
}

.loading-container, .empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  z-index: 999;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
  
  &.active {
    .tab-text {
      color: #ff6b6b;
    }
  }
}

.tab-icon {
  position: relative;
  margin-bottom: 8rpx;
}

.icon {
  width: 44rpx;
  height: 44rpx;
  display: block;
}

.bookshelf-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff6b6b;
  border-radius: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.badge-text {
  color: #fff;
  font-size: 20rpx;
  line-height: 1;
}

.tab-text {
  font-size: 22rpx;
  color: #666;
}
</style>